/**
 * Created by zhangjinrui on 17/6/27.
 */

public class Solution394 {

    public static void main(String args[]) {
        Solution394 s = new Solution394();
        System.out.println(s.decodeString("10[leetcode]"));
    }

    public String decodeString(String s) {
        if(countLR(s) == 0){
            return s;
        }

        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < s.length() ; i ++){
            if(!isNum(s.charAt(i))){
                sb.append(s.charAt(i));
            }else{
                int ed = find(s, i);
                String ns = s.substring(i, ed);
                int spilt = 0;
                while(isNum(ns.charAt(spilt))){
                    spilt ++;
                }
                int k = Integer.valueOf(ns.substring(0, spilt));
                String content = decodeString(ns.substring(spilt + 1, ns.length() - 1));
                sb.append(getKS(k, content));
                i = ed - 1;
            }
        }
        return sb.toString();
    }

    public int countLR(String s){
        int cnt = 0;
        for(int i = 0 ; i < s.length() ; i ++){
            if(s.charAt(i) == '['){
                cnt ++;
            }
        }
        return cnt;
    }

    public int find(String s, int st){
        int leftCnt = 0;
        int rightCnt = 0;
        while((leftCnt == 0 || rightCnt == 0) || (leftCnt != rightCnt) ){
            if(s.charAt(st) == '['){
                leftCnt ++;
            }else if(s.charAt(st) == ']'){
                rightCnt ++;
            }
            st ++;
        }
        return st;
    }

    public boolean isNum(char c){
        if(c >= '0' && c <= '9'){
            return true;
        }
        return false;
    }

    public String getKS(int k, String s){
        StringBuilder sb = new StringBuilder();
        while(k > 0){
            sb.append(s);
            k --;
        }
        return sb.toString();
    }
}
